package com.softa.common.service.impl;

import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.enums.TokenOrigin;
import com.baomidou.kisso.security.token.SSOToken;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.softa.common.annotation.ServiceLog;
import com.softa.common.constant.Constants;
import com.softa.common.dao.SysUserMapper;
import com.softa.common.dto.SysUserDTO;
import com.softa.common.entity.SysResource;
import com.softa.common.entity.SysRole;
import com.softa.common.entity.SysUser;
import com.softa.common.service.RoleService;
import com.softa.common.service.UserService;
import com.softa.common.sysconfig.shiro.encrypt.PasswordHelper;
import com.softa.common.sysconfig.support.DataTableRequest;
import com.softa.common.sysconfig.support.LoginRequest;
import com.softa.common.sysconfig.support.QueryRequest;
import com.softa.common.sysconfig.support.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@SuppressWarnings("all")
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private PasswordHelper passwordHelper;

    @Resource
    private RoleService roleService;

    /**
     * 创建用户
     * @param user
     */
    @Override
	@ServiceLog(value="创建用户")
    public String createUser(SysUser user) {
    	DataTableRequest dataGrid = new DataTableRequest();
    	dataGrid.getParams().put("username", user.getUsername());
        boolean isName=this.isExists(dataGrid);
    	String str="录入成功";
    	if(isName){
    		str="1";//存在名称
    	}else{
			 //加密密码
			passwordHelper.encryptPassword(user);
			sysUserMapper.insert(user);
    	}
        return str;
    }

    @Override
	@ServiceLog(value="更新用户")
    public String updateUser(SysUserDTO sysUserDTO) {
	  DataTableRequest dataGrid = new DataTableRequest();
	  dataGrid.getParams().put("id", sysUserDTO.getId());
	  dataGrid.getParams().put("username", sysUserDTO.getUsername());
	  boolean isName = this.isExists(dataGrid);
	  String str = "修改成功";
	  if (isName) {
		str = "1";//存在名称
	  } else {
		SysUser user = new SysUser();
		BeanUtils.copyProperties(sysUserDTO, user);
		sysUserMapper.updateById(user);
	  }
	  return str;
    }

    @Override
	@ServiceLog(value="删除用户")
    public void deleteUser(Long userId) {
    	SysUser sysUser = new SysUser();
		sysUser.setId(userId);
		sysUser.setIsshow(1);
    	sysUserMapper.updateById(sysUser);
    }

    public boolean isExists(DataTableRequest dataGrid){
    	List<SysUser> list=sysUserMapper.selectByParam(dataGrid);
    	boolean flag=false;
    	if(list.size() > 0){
    		flag=true;
    	}
    	return flag;
    }
    
    /**
     * 修改密码
     * @param userId
     * @param newPassword
     */
    @Override
	@ServiceLog(value="修改密码")
    public void changePassword(Long userId, String newPassword) {
    	SysUser user =sysUserMapper.selectById(userId);
        user.setPassword(newPassword);
        passwordHelper.encryptPassword(user);
        sysUserMapper.updateById(user);
    }

    @Override
	@ServiceLog(value="查询单个用户对象")
    public SysUser findOne(Long userId) {
        return sysUserMapper.selectById(userId);
    }

    @Override
	@ServiceLog(value="查询所有用户信息")
    public List<SysUser> findAll() {
        return sysUserMapper.selectByParam(new DataTableRequest<>());
    }

	/**
	 * 根据用户名查找用户
	 */
	@Override
	public SysUser findAdminUser() {
		DataTableRequest dataGrid = new DataTableRequest();
		dataGrid.getParams().put("username", Constants.ADMIN);
		List<SysUser> list = sysUserMapper.selectAdmin(dataGrid);
		if(list != null && list.size()>0){
			return list.get(0);
		}else{
			return null;
		}
	}


    /**
     * 根据用户名查找用户
     * @param username
     * @return
     */
    @Override
	public SysUser findByUsername(String username) {
		DataTableRequest dataGrid = new DataTableRequest();
    	dataGrid.getParams().put("username", username);
    	List<SysUser> list = sysUserMapper.selectByParam(dataGrid);
    	if(list != null && list.size()>0){
    		return list.get(0);
    	}else{
    		return null;
    	}
    }

    /**
     * 根据用户名查找其角色
     * @param username
     * @return
     */
    @Override
	public Set<String> findRoles(String username) {
    	SysUser user =findByUsername(username);
        if(user == null) {
            return Collections.EMPTY_SET;
        }
        return roleService.findRoles(this.getListRoleIds(user.getRoleIds()).toArray(new String[0]));
    }

    /**
     * 根据用户名查找其权限
     * @param username
     * @return
     */
    @Override
	public Set<String> findPermissions(String username) {
    	SysUser user =findByUsername(username);
        if(user == null) {
            return Collections.EMPTY_SET;
        }
        return roleService.findPermissions(this.getListRoleIds(user.getRoleIds()).toArray(new String[0]));
    }
    
    /**
     * 根据用户名查找其菜单
     * @param username
     * @return
     */
    @Override
	public List<SysResource> findResourceList(String username) {
    	SysUser user =findByUsername(username);
        if(user == null) {
            return Collections.EMPTY_LIST;
        }
        return roleService.findResourceList(this.getListRoleIds(user.getRoleIds()).toArray(new String[0]));
    }
    
    public List<String> getListRoleIds(String str){
   	 List<String> list=new ArrayList<String>();
   	 if(StringUtils.isEmpty(str)){
   		 return list;
   	 }
   	  String[] roleIdStrs = str.split(",");
	      for(String roleIdStr : roleIdStrs) {
	          if(StringUtils.isEmpty(roleIdStr)) {
	              continue;
	          }
	          list.add(roleIdStr);
	      }
	      return list;
   }


	@Override
	public Page<SysUserDTO> queryUserByParam(DataTableRequest request) {
		Page<SysUserDTO> page = request.startPagePlugin();
		Map<String, Object> params = request.getParams();
		QueryRequest queryRequest = new QueryRequest();
		queryRequest.setParams(params);
		List<SysUserDTO> list = sysUserMapper.selectByCondition(queryRequest);
		page.setRecords(list);
		List<SysUserDTO> userList = page.getRecords();
		for(SysUserDTO user : userList){
			user.setRoleName(this.getRoleName(user.getRoleIds()));
		}
		return  page;
	}


	@Override
	public Long queryUserTotalByParam(DataTableRequest dataGrid) {
		return sysUserMapper.selectCountByCondition(dataGrid);
	}

	public String getRoleName(String code){
		SysRole o=roleService.findOne(code);
		String str=null;
		if(o != null){
			str=o.getName();
		}
		return str;
	}

	/**
	 * 判断用户名是否存在
	 * @param user
	 */
	@Override
	public Integer checkusername(SysUser user) {
		DataTableRequest dataGrid = new DataTableRequest();
		dataGrid.getParams().put("username", user.getUsername());
		boolean isName=this.isExists(dataGrid);
		Integer status = 0;
		if(isName){
			status=1;//存在名称
		}
		return status;
	}

	@Override
	public Result login(HttpServletResponse response, HttpServletRequest request, LoginRequest loginReq){
		//TODO 验证码、错误次数、要不要允许一个人登录
		SysUser sysUser = null;
        String username = loginReq.getUserName();
		if(Constants.ADMIN.equals(username)){
			sysUser = findAdminUser();
		}else{
			sysUser = findByUsername(username);
		}
		//成功
		Integer resultCode = 10001;
		String message = "登录成功";
		if(sysUser == null){
			//失敗
			resultCode = 10002;
			message = "登录失败";
		}else{
			SysUser user = new SysUser();
			user.setPassword(loginReq.getPassword());
			passwordHelper.encryptPassword(user, sysUser.getSalt());
			if(user.getPassword().equals(sysUser.getPassword())){
				SSOHelper.clearLogin(request, response);
				// 设置登录 COOKIE
				SSOToken ssoToken = new SSOToken();
				ssoToken.setId(sysUser.getUsername());
				ssoToken.setIp(request);
				ssoToken.setOrigin(TokenOrigin.values()[loginReq.getLoginType()]);
				SSOHelper.setCookie(request, response, ssoToken, false);
			}else{
				//密碼錯誤
				resultCode = 10003;
				message = "密码错误";
			}
		}
		return Result.toSucess(resultCode, message);
	}

}
